package com.ebupt.migu.music.commons.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@Slf4j
public class FtpUtil {

    /**
     *  连接ftp服务器
     */
    public static FTPClient getClient(String ip, int port, String user, String pwd, String ftpPath){
        FTPClient ftpClient = null;
        try {
            ftpClient = new FTPClient();
            //连接ftp
            ftpClient.connect(ip,port);
            //登录ftp
            boolean result = ftpClient.login(user,pwd);
            if(!result){
                log.info("未连接到FTP，用户名或密码错误");
            }else{
                log.info("FTP连接成功");
            }
            //设置编码格式
            ftpClient.setControlEncoding("UTF-8");
            //设置被动模式
            ftpClient.enterLocalPassiveMode();
            //切换工作路径
            ftpClient.changeWorkingDirectory(ftpPath);
            log.info("切换到工作目录：{}",ftpPath);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("FTP连接失败，网络不通或者ip端口配置有误");
        }
        return ftpClient;
    }

    /**
     * @param ftpPath
     * @return function:读取指定目录下的文件名
     * @throws IOException
     */
    public static List<String> getFileNameList(String ftpPath, FTPClient client) {
        List<String> fileNameLists = new ArrayList<String>();
        // 获得指定目录下所有文件名
        FTPFile[] ftpFiles = null;
        try {
            ftpFiles = client.listFiles(ftpPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (int i = 0; ftpFiles != null && i < ftpFiles.length; i++) {
            FTPFile file = ftpFiles[i];
            if (file.isFile()) {
                fileNameLists.add(file.getName());
            }
        }
        return fileNameLists;
    }
    /**
     * 从远端FTP服务器上读取文件
     */
    public static List<String> readFile(String fileName, FTPClient client){
        //获取FTP连接
        if(client == null){
            log.info("请先获取FTP连接");
            return null;
        }
        List<String> list = new LinkedList<>();
        InputStream is = null;
        try {
            //读文件
            is = client.retrieveFileStream(fileName);
            if(is != null){
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String data;
                log.info("开始读取文件：{}",fileName);
                while ((data = br.readLine())!= null) {
                    //去空白判断
                    if(data.trim().length()>2){
                        list.add(data);
                    }
                }
                br.close();
                is.close();
                client.getReply();
            }else{
                log.info("文件为空，不能读取：{}",fileName);
            }
        } catch (IOException e) {
            log.info("读取文件失败：{}",fileName);
            e.printStackTrace();
        }
        return list;
    }

    /**
     *   退出登录，关闭连接
     */
    public static void closeServer(FTPClient client) {
        if (client.isConnected()) {
            try {
                client.logout();
                client.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        String ip = "218.200.160.122";
        int port = 21;
        String path = "/fine-operation/msg/";
        String user = "wxtk";
        String pwd = "pyZx2{g0";
        FTPClient ftpClient = FtpUtil.getClient(ip,port,user,pwd,path);
        System.out.println(FtpUtil.getFileNameList(path,ftpClient).toString());
        System.out.println(FtpUtil.readFile("message_20200924_001.txt",ftpClient));
        System.out.println(FtpUtil.readFile("msgPVUV_20200924.txt",ftpClient));
    }

}
